window.addEventListener('DOMContentLoaded', () => {
  app.initPage();
});

function loadPage() {
  layui.use(['element', 'layer'], () => {
    $.ajax({
      url: app.urlLocation.queryAllCt,
      type: 'get',
      success: function (data) {
        let html = '';
        $.each(data, function (i, v) {
          html += `<option value="${v.id}">${v.classType}</option>`;
        });
        $('select[name=subjectClazz]').append(html);
        app.resetForm();
      },
      error: function () {
        alertInfo('网站服务出现异常，请联系管理员!');
      }
    });
  });
  create();
}

function create() {
  layui.use(['form', 'layer'], () => {
    let form = layui.form,
      layer = layui.layer;
    form.on('submit(create)', obj => {
      let field = obj.field;
      let layuiCard = $('.layui-card'),               // 获取包裹每个题目的盒子
        testTitle = field.testTitle,                  // 获取试题主题
        testClazz = field.subjectClazz,               // 试题所属科目
        singleScale = parseFloat(field.singleScale),  // 单选题分值
        multiScale = parseFloat(field.multiScale),    // 多选题分值
        openScale = 0,                                // 开放题分值
        testTime = parseInt(field.restrict),          // 设定考试时间
        createdBy = $('#name').text();                // 获取当前登录人名称，用作试题创建人
      let subjectBank = [], // 设定题库数组，用于存储所有的题目
        testBank = [],      // 设定试题数组，用于存储当前试题信息
        sumScale = 0;       // 试题总分
      for (let i = 0; i < layuiCard.length; i++) {
        let curLayuiCard = layuiCard.eq(i),
          curQuestionInfo = {},
          singleTest = {},  // 设定题目数组，用于存储每道题的信息 ( 包括分值等信息 )
          subjectType = layuiCard.eq(i).find('.ques-type').text(),        // 获取题目类型
          subjectTitle = curLayuiCard.find('input[name=question]').val(); // 题目内容
        // 对题目类型进行判断：1. 单选；2. 多选；3. 开放题
        switch (subjectType) {
          case '1':
            let singleOptionAnswer = curLayuiCard.find('input[name=option]'),
              // 定义存放选项内容的数组
              singleSubjectContent = [];
            for (let i = 0; i < singleOptionAnswer.length; i++) {
              // 将选项内容存到数组中
              singleSubjectContent[i] = singleOptionAnswer.eq(i).val();
            }
            // 将数组转为字符串，以 '|' 符隔开
            singleSubjectContent = singleSubjectContent.join('|');
            // 获取当前单选题的答案值
            let subjectAnswer = curLayuiCard.find('.layui-form-radioed').prev('input[type=radio]:checked').val();
            curQuestionInfo.subjectTitle = subjectTitle;
            curQuestionInfo.subjectType = subjectType;
            curQuestionInfo.subjectContent = singleSubjectContent;
            curQuestionInfo.subjectAnswer = subjectAnswer;
            curQuestionInfo.subjectClazz = testClazz;
            curQuestionInfo.createdBy = createdBy;
            sumScale += singleScale;
            break;
          case '2':
            let multiOptionAnswer = curLayuiCard.find('input[name=option]'),
              // 定义存放选项内容的数组
              multiSubjectContent = [];
            for (let i = 0; i < multiOptionAnswer.length; i++) {
              // 将选项内容存到数组中
              multiSubjectContent[i] = multiOptionAnswer.eq(i).val();
            }
            // 将数组转为字符串，以 '|' 符隔开
            multiSubjectContent = multiSubjectContent.join('|');
            // 获取当前题目的参考答案
            let multiSubjectAnswer = curLayuiCard.find('.layui-form-checked').prev('input[type=checkbox]'),
              multiSubjectAnswerArr = [];
            for (let i = 0; i < multiSubjectAnswer.length; i++) {
              multiSubjectAnswerArr[i] = multiSubjectAnswer.eq(i).val();
            }
            // 将参考答案转为字符串
            multiSubjectAnswerArr = multiSubjectAnswerArr.join('|');
            curQuestionInfo.subjectTitle = subjectTitle;
            curQuestionInfo.subjectType = subjectType;
            curQuestionInfo.subjectContent = multiSubjectContent;
            curQuestionInfo.subjectAnswer = multiSubjectAnswerArr;
            curQuestionInfo.subjectClazz = testClazz;
            curQuestionInfo.createdBy = createdBy;
            sumScale += multiScale;
            break;
          case '3':
            let openQuestionAnswer = curLayuiCard.find('textarea').val(); // 开放题参考答案
            curQuestionInfo.subjectTitle = subjectTitle;
            curQuestionInfo.subjectType = subjectType;
            curQuestionInfo.subjectAnswer = openQuestionAnswer;
            curQuestionInfo.subjectClazz = testClazz;
            curQuestionInfo.createdBy = createdBy;
            openScale = parseFloat(curLayuiCard.find('input[name=openScale]').val());
            sumScale += openScale;
            break;
        }
        subjectBank.push(curQuestionInfo);
        singleTest.testTitle = testTitle;
        singleTest.testNo = i + 1;
        if (subjectType === '1')
          singleTest.singleScale = singleScale;
        else if (subjectType === '2')
          singleTest.singleScale = multiScale;
        else
          singleTest.singleScale = openScale;
        singleTest.sumScale = sumScale;
        singleTest.testClazz = testClazz;
        singleTest.testTime = testTime;
        singleTest.createdBy = createdBy;
        testBank.push(singleTest);
      }
      let data = [];
      data.push(JSON.stringify(subjectBank));
      data.push(JSON.stringify(testBank));
      data = data.join('|||');
      $.post(`${app.urlLocation.addCusTestPaper}`, {dataString: data}, res => {
        if (res === 500) {
          layer.msg('试题创建失败，请重试或联系系统管理员');
        } else {
          layer.msg('试题创建成功，正在进行跳转');
          setTimeout(() => {
            window.location.href = '/teacher-action/test';
          }, 1000)
        }
      });
    })
  })
}

function returnToTest() {
  layui.use('layer', () => {
    let layer = layui.layer;
    layer.confirm('现在返回将丢失当前页码所有试题内容，是否跳转?', {
      btn: ['跳转', '不跳转']
    }, () => {
      window.location.href = '/teacher-action/test';
    })
  })
}

function certainType(e) {
  let questionType = e.parents('.question-type').find('.layui-form-radioed').find('div').text();
  questionType = (questionType === '单选') ? 1 : (questionType === '多选') ? 2 : 3;
  e.parents('.layui-card').find('.ques-type').text(questionType);
  let index = $('.layui-card').length;
  if (questionType !== 3) {
    e.parents('.layui-card-body').html(optionHtml(index, questionType));
  } else {
    let input = '<input type="text" name="title" placeholder="请输入题目分值" ' +
      'class="layui-input layui-input-radius open" title="" autocomplete="off" lay-verify="required">';
    e.parents('.layui-card').find('.layui-card-header').find('input[name=title]').addClass('open').after(input);
    e.parents('.layui-card-body').html(publicHtml(index));
  }
  resetForm();
}

function addOption(e) {
  let parents = e.parents('.layui-input-block');
  let prevParents = parents.prev('div');
  prevParents.find('i').remove();
  parents.before(addOneOptionHtml(e.parents('.layui-card').index() + 1));
  resetForm();
}

function addQuestion() {
  let layuiCard = $('.layui-card');
  let length = layuiCard.length;
  layuiCard.eq(length - 1).after(layuiCardHtml());
  layuiCard = $('.test-content .layui-card');
  layuiCard.eq(length).find('.layui-card-body').html(questionTypeHtml(length));
  layuiCard.eq(length).find('.question-no').text(length + 1);
  resetForm();
}

function delOption(e) {
  layui.use('layer', function () {
    layer.confirm('删除后将不可恢复，是否删除该选项？', {
      btn: ['删除', '算了']
    }, function () {
      let i = '<i class="layui-icon layui-icon-delete" onclick="delOption($(this));"></i>';
      e.parents('.layui-input-block').prev('div').find('input').eq(1).after(i);
      e.parents('.layui-input-block').remove();
      layer.msg('选项已删除');
    });
  });
}

function delQuestion(e) {
  layui.use('layer', function () {
    layer.confirm('删除后将不可恢复，是否删除该题目？', {
      btn: ['删除', '算了']
    }, function () {
      let layuiCard = e.parents('.layui-card');
      let index = layuiCard.index() + 1;
      let length = $('.test-content .layui-card').length;
      if (index === length) {
        $('.test-content').find('.layui-card').eq(index - 1).remove();
      } else {
        layuiCard = $('.test-content').find('.layui-card');
        layuiCard.eq(index - 1).remove();
        for (let i = index - 1; i < length; i++) {
          layuiCard.eq(i).find('.question-no').text(parseInt(layuiCard.eq(i).find('.question-no').text()) - 1);
        }
      }
      layer.msg('题目已删除');
    });
  });
}

function layuiCardHtml() {
  return '<div class="layui-card"><div class="layui-card-header">' +
    '<label class="layui-form-label">第<span class="question-no">1</span>题</label><div class="layui-input-block">' +
    '<input type="text" name="question" placeholder="请输入题目内容" class="layui-input layui-input-radius"' +
    ' autocomplete="off" lay-verify="required">' +
    '<i class="layui-icon layui-icon-delete" onclick="delQuestion($(this));"></i></div>' +
    '<span class="ques-type"></span></div><div class="layui-card-body"></div></div>';
}

function optionHtml(index, questionType) {
  let input = '<input type="radio" name="answer' + index + '" title="" ';
  input += questionType === 1 ? 'value="1">' : 'lay-skin="primary">';
  return '<div class="layui-input-block">' +
    '<input type="text" name="option" placeholder="请输入选项内容" class="layui-input layui-input-radius"' +
    ' autocomplete="off" lay-verify="required">' + input +
    '</div><div class="layui-input-block">' +
    '<input type="text" name="option" placeholder="请输入选项内容" class="layui-input layui-input-radius"' +
    ' autocomplete="off" lay-verify="required">' + input +
    '</div><div class="layui-input-block">' +
    '<input type="text" name="option" placeholder="请输入选项内容" class="layui-input layui-input-radius"' +
    ' autocomplete="off" lay-verify="required">' + input +
    '</div><div class="layui-input-block">' +
    '<input type="text" name="option" placeholder="请输入选项内容" class="layui-input layui-input-radius"' +
    ' autocomplete="off" lay-verify="required">' + input +
    '<i class="layui-icon layui-icon-delete" onclick="delOption($(this));"></i></div>' +
    '<div class="layui-input-block">' +
    '<button type="button" class="layui-btn layui-btn-radius layui-btn-primary" onclick="addOption($(this));">' +
    '添加选项</button></div>';
}

function addOneOptionHtml(index) {
  let layuiCard = $('.layui-card');
  let classType = layuiCard.eq(index - 1).find('.ques-type').text();
  let inputStr;
  let inputLength = layuiCard.eq(index - 1).children('.layui-card-body').find('.layui-input-block').length;
  if (classType === '1') {
    inputStr = '<input type="radio" name="answer' + index + '" value="' + inputLength + '" title=""' +
      ' autocomplete="off" lay-verify="required">';
  } else {
    inputStr = '<input type="checkbox" name="answer2" value="' + inputLength + '" lay-skin="primary"' +
      ' autocomplete="off" lay-verify="required">';
  }
  return '<div class="layui-input-block">' +
    '<input type="text" name="option" placeholder="请输入选项内容" class="layui-input layui-input-radius">' +
    inputStr + '<i class="layui-icon layui-icon-delete" onclick="delOption($(this));"></i></div>';
}

function publicHtml(index) {
  return '<div class="layui-input-block">' +
    '<textarea name="answer' + index + '" placeholder="请输入参考答案" class="layui-textarea"' +
    ' lay-verify="required"></textarea></div>';
}

function questionTypeHtml(index) {
  return '<div class="question-type">' +
    '<input type="radio" name="question-type' + (index + 1) + '" value="单选" title="单选" checked>' +
    '<input type="radio" name="question-type' + (index + 1) + '" value="多选" title="多选">' +
    '<input type="radio" name="question-type' + (index + 1) + '" value="开放漆" title="开放题">' +
    '<button type="button" class="layui-btn layui-btn-radius layui-btn-primary check-type" ' +
    'onclick="certainType($(this));">确定类型</button></div>';
}

function resetForm() {
  layui.use('form', function () {
    let form = layui.form;
    form.render();
  });
}

function showLayout(times) {
  $('.layout-background').css('display', 'block');
  let layoutBox = $('#layout .layout-box');
  $('#layout .layout-background').animate({
    opacity: '.5'
  }, times);
  $('.layout-box').css('display', 'block');
  layoutBox.animate({
    margin: '-' + layoutBox.outerHeight(false) / 2 + ' 0 0 -200px',
    opacity: '1'
  }, times);
}

function hideLayout(times) {
  $('#layout .layout-background').animate({
    opacity: '0'
  }, times);
  $('#layout .layout-box').animate({
    margin: '-160px 0 0 -200px',
    opacity: '0'
  }, times);
  setTimeout(function () {
    $('.layout-background').css('display', 'none');
    $('.layout-box').css('display', 'none');
    $('#layout form').find('input, textarea').val('');
  }, times);
}

function isFloat(number) {
  return /^(-?\d*\.\d+|\d*)$/.test(number);
}

function isNumber(number) {
  return /^\d*$/.test(number);
}

$('input[name=singleScale], input[name=multiScale], input[name=openScale]').keyup(function () {
  let reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
  if (reg.test(this.value)) {
    this.value = '';
  } else {
    if (!this.value.match(/^[+\-]?\d*?\.?\d*?$/))
      this.value = this.value.substring(0, this.value.length - 1);
  }
});

$('input[name=restrict]').keyup(function () {
  let reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
  if (reg.test(this.value)) {
    this.value = '';
  } else {
    if (!this.value.match(/^\d*?$/))
      this.value = this.value.substring(0, this.value.length - 1);
  }
});